﻿using MLSMooc.BO;
using MLSMooc.DAO.Implement.Project;
using MLSMooc.Service.Interface.Project;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using Dapper;
using MLSMooc.Helper;

namespace MLSMooc.Service.Implement.Project
{
   public class ProjectServiceImpl : IProjectService
    {
        private static ProjectServiceImpl instance = new ProjectServiceImpl();

        private ProjectServiceImpl() { }
        public static ProjectServiceImpl Getinstance() => instance;

        public static ProjectDAO projectDAO = ProjectDAO.Getinstance();

        public async Task<int> UpProBrowseCount(int id)
        {
            using (SqlConnection conn=new SqlConnection(SalesSysSqlHelper.connectionString))
            {
                StringBuilder sql = new StringBuilder();
                sql.Append($@"update Mooc_Project set Pro_BrowseNumber=Pro_BrowseNumber+1 where Id=@id");
                var res = await conn.ExecuteAsync(sql.ToString(), new { id = id });
                return res;
            }
        }

        public async Task<int> UpMenuBrowseCount(int id)
        {
            using (SqlConnection conn = new SqlConnection(SalesSysSqlHelper.connectionString))
            {
                StringBuilder sql = new StringBuilder();
                sql.Append($@"update Mooc_Resource_Menu set BrowseCount=BrowseCount+1 where Type=1 and ResourceId=@id");
                var res = await conn.ExecuteAsync(sql.ToString(), new { id = id });
                return res;
            }
        }

        public async Task<int> InsertProBrowseInfo(BrowseBO data)
        {
            using (SqlConnection conn=new SqlConnection(SalesSysSqlHelper.connectionString))
            {
                StringBuilder sql = new StringBuilder();
                sql.Append($@"insert into Mooc_ProBrowseInfo values(@AdminId,@ResourceId,@StartTime,@EndTime,'',getdate(),getdate(),0)");
                var res = await conn.ExecuteAsync(sql.ToString(), new { AdminId = data.AdminId, ResourceId = data.ResourceId, StartTime = data.StartTime, EndTime = data.EndTime });

                if (res<1)
                {
                    return 0;
                }
                else
                {
                                await UpMenuBrowseCount(data.ResourceId);
                    var res1 = await UpProBrowseCount(data.ResourceId);
                    
                    return res1;
                }
                
            }
        }
    }
}
